package com.xyoto.community.service.impl;

import com.github.pagehelper.PageHelper;
import com.xyoto.community.constant.*;
import com.xyoto.community.dto.PageDTO;
import com.xyoto.community.entity.main.AnonymousUser;
import com.xyoto.community.entity.main.Dynamic;
import com.xyoto.community.entity.main.Message;
import com.xyoto.community.enums.CommonEnum;
import com.xyoto.community.enums.MessageEnum;
import com.xyoto.community.enums.WechatLoginEnum;
import com.xyoto.community.exception.ExceptionUtils;
import com.xyoto.community.mapper.comment.DynamicCommentMapper;
import com.xyoto.community.mapper.comment.DynamicCommentReplyMapper;
import com.xyoto.community.mapper.main.*;
import com.xyoto.community.mapper.picture.DynamicPictureMapper;
import com.xyoto.community.po.*;
import com.xyoto.community.service.*;
import com.xyoto.community.utils.JwtUtils;
import com.xyoto.community.utils.PageUtils;
import com.xyoto.community.utils.RedisCommonUtils;
import com.xyoto.community.utils.Result;
import com.xyoto.community.vo.InteractMessageListVO;
import com.xyoto.community.vo.MessageFansListVO;
import com.xyoto.community.vo.MessageListVO;
import com.xyoto.community.vo.PrivateLetterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author coderFu
 * @create 2021/10/5
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Resource
    private HttpServletRequest request;

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private DynamicCommentMapper dynamicCommentMapper;

    @Resource
    private DynamicCommentReplyMapper dynamicCommentReplyMapper;

    @Resource
    private FanFollowMapper fanFollowMapper;


    @Resource
    private DynamicMapper dynamicMapper;

    @Resource
    private DynamicPictureMapper dynamicPictureMapper;

    @Resource
    private TopicMapper topicMapper;

    @Autowired
    private RedisCommonUtils redisCommonUtils;

    @Autowired
    private AnonyUserService anonyUserService;

    @Autowired
    private PrivateLetterService privateLetterService;

    @Autowired
    private UserTitleService userTitleService;

    @Autowired
    private UserTitleCacheService userTitleCacheService;

    @Override
    public Result getMessageList() {
        MessageListVO messageListVo = new MessageListVO();
        //获取用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(request);
        if (userId == 0) {
            ExceptionUtils.error(WechatLoginEnum.USER_NOT_LOGIN);
        }

        //查询用户是否有最新的互动消息若有则取出第一条
        log.info("获取最新的消息记录");
        NewestInteractMessagePO newestInteractMessagePo = messageMapper.getNewestMessage(userId);


        if (newestInteractMessagePo == null) {
            //无最新未读数数据,初始化返回结果
            messageListVo.init();
        } else {
            //查询未读消息个数
            Integer count = messageMapper.getUnreadCount(userId);
            //有最新未读数据, 通过类型调用不同的逻辑处理方法
            log.info("查询用户基本信息");
            UserPO userPo = userMapper.getUserPartInfoById(newestInteractMessagePo.getUserId());
            NewestInteractMessageDetailsPO oneNewestInteractMessage = getOneNewestInteractMessage(newestInteractMessagePo, userPo);
            //装入未读消息个数
            oneNewestInteractMessage.setCount(count);
            //装入返回对象中
            messageListVo.setNewestInteractMessageDetailsPo(oneNewestInteractMessage);
        }

        //获取最新的粉丝互动消息
        //判断是否有最新的粉丝关注数据
        log.info("判断是否有最新的粉丝关注信息");

        MessageNewestFanMessagePO messageNewestFanMessagePO = messageMapper.getNewestFanMessage(userId, ModuleType.USER_FOLLOW);
        NewestFanMessagePO newestFanMessagePo = new NewestFanMessagePO();
        if (messageNewestFanMessagePO != null) {
            //获取用户信息
            UserPO userPo = userMapper.getUserPartInfoById(messageNewestFanMessagePO.getUserId());
            if (userPo != null) {
                newestFanMessagePo.setNickname(userPo.getNickname());
            } else {
                newestFanMessagePo.setNickname("");
            }
            //查询最新未读关注数目
            Integer followCount = messageMapper.getUnReadFollowCount(userId);
            newestFanMessagePo.setStatus(messageNewestFanMessagePO.getType());
            newestFanMessagePo.setCreateTime(messageNewestFanMessagePO.getCreateTime());
            newestFanMessagePo.setCreateTime(messageNewestFanMessagePO.getCreateTime());
            newestFanMessagePo.setCount(followCount);
        } else {
            newestFanMessagePo.setStatus(MessageConstant.NO_NEWEST_STATUS);
        }
        //装入返回对象中
        messageListVo.setNewestFanMessagePo(newestFanMessagePo);
        List<PrivateLetterVo> privateLetterList = privateLetterService.getPrivateLetterList();
        messageListVo.setPrivateLetterVos(privateLetterList);
        return Result.success(messageListVo);
    }


    @Override
    public Result getInteractMessageList(PageDTO pageDTO) {
        //获取消息用户id
        Integer targetUserId = JwtUtils.getMemberIdByJwtToken(request);
        if (targetUserId == 0) {
            ExceptionUtils.error(WechatLoginEnum.USER_NOT_LOGIN);
        }
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        //获取最新的互动消息列表
        //无数据情形
        List<NewestInteractMessagePO> interactMessagePoList = messageMapper.getNewestInteractMessageList(targetUserId, pageDTO.getEndIndexId());
        if (interactMessagePoList == null || interactMessagePoList.size() <= 0) {
            return Result.success(PageUtils.restPage(new ArrayList<NewestFanMessagePO>()));
        }
        //处理数据的逻辑部分
        List<InteractMessageListVO> interactMessageListVo = getInteractMessageDeal(interactMessagePoList, pageDTO.getPageSize());
        //判断是否有需要更新的状态
        NewestInteractMessagePO newestInteractMessagePo = messageMapper.getNewestMessage(targetUserId);
        if (newestInteractMessagePo != null) {
            //更新互动消息读取状态
            Integer integer = messageMapper.updateInteractMessageReadStatus(targetUserId);
            if (integer < DatabaseOperationResult.SUCCESS) {
                log.info("互动消息读取状态更新失败");
            }
            log.info("互动消息读取状态更新成功");
        }
        return Result.success(PageUtils.restPage(interactMessagePoList, interactMessageListVo));
    }

    @Override
    public Result getFansMessageList(PageDTO pageDTO) {
        //获取用户的id
        Integer targetUserId = JwtUtils.getMemberIdByJwtToken(request);
        if (targetUserId == 0) {
            ExceptionUtils.error(WechatLoginEnum.USER_NOT_LOGIN);
        }
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        //查询用户粉丝消息列表数据
        List<MessageNewestFanMessagePO> messageNewestFanMessagePo = messageMapper.getFansMessageList(targetUserId);
        if (messageNewestFanMessagePo.size() <= 0) {
            return Result.success(PageUtils.restPage(new ArrayList<>()));
        }


        //获取用户id集合
        List<Integer> userIds = messageNewestFanMessagePo.stream().map(MessageNewestFanMessagePO::getUserId).collect(Collectors.toList());
        // userFollowStatusMap = {<上述用户id中我关注的用户的id，我对我关注用户的关注表记录>}
        HashMap<Integer, UserFollowStatusPO> userFollowStatusMap = new HashMap<>(16);
        HashMap<Integer, UserPO> userMap = new HashMap<>(16);
        //获取用户的信息
        List<UserPO> userSimpleList = userMapper.getUserSimpleList(userIds);
        if (userSimpleList.size() > 0) {
            for (UserPO userPO : userSimpleList) {
                userMap.put(userPO.getId(), userPO);
            }
            //判断互相关注的状态
            List<UserFollowStatusPO> userFollowStatusList = fanFollowMapper.getUserFollowStatusList(targetUserId, userIds);
            // for循环完后，userFollowStatusMap的大小 等于 userFollowStatusList的大小
            for (UserFollowStatusPO userFollowStatusPO : userFollowStatusList) {
                userFollowStatusMap.put(userFollowStatusPO.getTargetId(), userFollowStatusPO);
            }
        }

        //拼接结果
        List<MessageFansListVO> messageFansListVo = new ArrayList<>(pageDTO.getPageSize());
        for (MessageNewestFanMessagePO messageNewestFanMessagePO : messageNewestFanMessagePo) {
            MessageFansListVO messageFansListVO = new MessageFansListVO();
            messageFansListVO.setId(messageNewestFanMessagePO.getId());
            messageFansListVO.setCreateTime(messageNewestFanMessagePO.getCreateTime());
            //插入用户信息
            UserPO userPO = userMap.get(messageNewestFanMessagePO.getUserId());
            if (userPO != null) {
                messageFansListVO.setUserId(userPO.getId());
                messageFansListVO.setNickname(userPO.getNickname());
                messageFansListVO.setAvatarUrl(userPO.getAvatarUrl());
                messageFansListVO.setSignature(userPO.getSignature());
            }

            //插入关注状态
            UserFollowStatusPO userFollowStatusPO = userFollowStatusMap.get(messageNewestFanMessagePO.getUserId());
            if (userFollowStatusPO != null) {
                messageFansListVO.setFollowStatus((short) 3);
            }
            messageFansListVo.add(messageFansListVO);
        }
        //所有未读变已读
        MessageNewestFanMessagePO messageNewestFanMessagePO = messageMapper.getNewestFanMessage(targetUserId, ModuleType.USER_FOLLOW);
        if (messageNewestFanMessagePO != null) {
            Integer integer = messageMapper.updateFanMessageReadStatus(targetUserId);
            if (integer < DatabaseOperationResult.SUCCESS) {
                log.info("粉丝消息读取状态更新失败");
            }
            log.info("粉丝消息读取状态更新成功");
        }
        return Result.success(PageUtils.restPage(messageNewestFanMessagePo, messageFansListVo));
    }

    @Override
    public List<InteractMessageListVO> getInteractMessageDeal(List<NewestInteractMessagePO> interactMessagePoList, Integer pageSize) {
        //获存储所有用户的id
        List<Integer> userIds = new ArrayList<>(pageSize);
        //存储动态的id
        List<Integer> dynamicIds = new ArrayList<>(pageSize);
        //存储动态评论的id
        List<Integer> dynamicCommentIds = new ArrayList<>(pageSize);
        //存储动态评论回复的id
        List<Integer> dynamicReplyIds = new ArrayList<>(pageSize);
        //存储图片的集合
        HashMap<Integer, List<DynamicPicturePO>> pictureMap = new HashMap<>(16);
        for (NewestInteractMessagePO newestInteractMessagePo : interactMessagePoList) {
            userIds.add(newestInteractMessagePo.getUserId());
            Short type = newestInteractMessagePo.getType();
            //构件存储图片的集合
            List<DynamicPicturePO> dynamicPicturePOList = new ArrayList<>(pageSize);
            pictureMap.put(newestInteractMessagePo.getThirdParentId(), dynamicPicturePOList);
            dynamicIds.add(newestInteractMessagePo.getThirdParentId());
            if (type == ModuleType.DYNAMIC_COMMENT) {
                dynamicCommentIds.add(newestInteractMessagePo.getModuleId());
            } else if (type == ModuleType.DYNAMIC_COMMENT_REPLY) {
                //判断是否为回复的回复
                if (newestInteractMessagePo.getZeroParentId() != null) {
                    dynamicReplyIds.add(newestInteractMessagePo.getFirstParentId());
                }
                dynamicReplyIds.add(newestInteractMessagePo.getModuleId());
                dynamicCommentIds.add(newestInteractMessagePo.getSecondParentId());
            } else if (type == ModuleType.DYNAMIC_COMMENT_LOVE) {
                dynamicCommentIds.add(newestInteractMessagePo.getSecondParentId());
            } else if (type == ModuleType.DYNAMIC_COMMENT_REPLY_LOVE) {
                //判断是否对回复的回复点赞
                if (newestInteractMessagePo.getZeroParentId() != null) {
                    dynamicReplyIds.add(newestInteractMessagePo.getZeroParentId());
                }
                dynamicReplyIds.add(newestInteractMessagePo.getFirstParentId());
                dynamicCommentIds.add(newestInteractMessagePo.getSecondParentId());
            }
        }

        //查询用户信息
        List<UserPO> userSimpleList = userMapper.getUserSimpleList(userIds);
        //构造存储用户信息
        HashMap<Integer, UserPO> userMap = new HashMap<>(16);
        for (UserPO userPO : userSimpleList) {
            userMap.put(userPO.getId(), userPO);
        }
        //初始化内容容器
        HashMap<Integer, ContentDetailsPO> contentDetailsMap = null;

        //查询动态信息
        if (dynamicIds.size() != 0) {
            //查询动态列表
            List<TotalMessageDynamicListPO> contentDetailsPoList = dynamicMapper.getDynamicListByIds(dynamicIds);

            //查询动态的图片
            List<DynamicPicturePO> dynamicPicturePoList = dynamicPictureMapper.getDynamicPictureList(dynamicIds);

            //构造图片的存储
            for (DynamicPicturePO dynamicPicturePO : dynamicPicturePoList) {
                List<DynamicPicturePO> dynamicPicturePOLists = pictureMap.get(dynamicPicturePO.getKeyId());
                dynamicPicturePOLists.add(dynamicPicturePO);
            }

            //获取话题的id
            List<Integer> topicIds = contentDetailsPoList.stream().map(TotalMessageDynamicListPO::getTopicId).collect(Collectors.toList());
            //查询动态的话题
            HashMap<Integer, TopicSimplePO> topicMap = null;
            if (topicIds.size() != 0) {
                List<TopicSimplePO> topicSimplePo = topicMapper.getTopicSimpleList(topicIds);
                //构建话题的存储
                topicMap = new HashMap<>(16);
                for (TopicSimplePO topicSimplePO : topicSimplePo) {
                    topicMap.put(topicSimplePO.getTopicId(), topicSimplePO);
                }
            }

            //构建存储内容的信息
            contentDetailsMap = new HashMap<>(16);

            //拼接动态存储结果的集
            for (TotalMessageDynamicListPO dynamicListPo : contentDetailsPoList) {
                //拼接用户信息
                ContentDetailsPO contentDetailsPo = new ContentDetailsPO();
                contentDetailsPo.setContent(dynamicListPo.getContent());
                contentDetailsPo.setId(dynamicListPo.getId());
                contentDetailsPo.setUserId(dynamicListPo.getUserId());
                if (Integer.valueOf(AnonymousStatus.ANONYMOUS).equals(dynamicListPo.getStatus())){
                    //改动态为匿名状态，显示匿名信息
                    Integer anonymousUserId = dynamicListPo.getAnonymousUserId();
                    AnonymousUser anonymousUser = anonyUserService.getAnonymousUserById(anonymousUserId);
                    contentDetailsPo.setAvatarUrl(anonymousUser.getAnonymousAvatarUrl());
                    contentDetailsPo.setNickname(anonymousUser.getAnonymousName());
                    contentDetailsPo.setStatus(dynamicListPo.getStatus());
                }else {

                    contentDetailsPo.setNickname(dynamicListPo.getNickName());
                    contentDetailsPo.setAvatarUrl(dynamicListPo.getAvatarUrl());

                    // 获取头衔信息
                    UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(dynamicListPo.getTitleNameId(), dynamicListPo.getTitleLogoId());
                    contentDetailsPo.setUserTitlePO(userTitlePo);
                }

                //添加话题信息
                TopicSimplePO topicSimplePO = topicMap == null ? null : topicMap.get(dynamicListPo.getTopicId());
                if (topicSimplePO != null) {
                    contentDetailsPo.setTopicId(topicSimplePO.getTopicId());
                    contentDetailsPo.setTitle(topicSimplePO.getTitle());
                }
                //添加图片信息
                List<DynamicPicturePO> dynamicPicturePOLists = pictureMap.get(dynamicListPo.getId());
                contentDetailsPo.setDynamicPicturePo(dynamicPicturePOLists);
                contentDetailsMap.put(dynamicListPo.getId(), contentDetailsPo);
            }
        }

        HashMap<Integer, MessageDynamicCommentPO> dynamicCommentMap = null;
        //查询动态评论内容查询
        if (!dynamicCommentIds.isEmpty()) {
            //查询评论内容
            List<MessageDynamicCommentPO> dynamicCommentPo = dynamicCommentMapper.getDynamicCommentContent(dynamicCommentIds);
            //构造数据集合
            dynamicCommentMap = new HashMap<>(16);
            for (MessageDynamicCommentPO commentPo : dynamicCommentPo) {
                dynamicCommentMap.put(commentPo.getId(), commentPo);
            }
        }
        HashMap<Integer, MessageDynamicCommentReplyPO> dynamicCommentReplyMap = null;
        // 查询动态回复内容
        if (!dynamicReplyIds.isEmpty()) {
            //查询评论内容
            List<MessageDynamicCommentReplyPO> dynamicCommentReplyPo = dynamicCommentReplyMapper.getDynamicCommentReplyListByIds(dynamicReplyIds);
            //构造数据集合
            dynamicCommentReplyMap = new HashMap<>(16);
            for (MessageDynamicCommentReplyPO commentReplyPo : dynamicCommentReplyPo) {
                dynamicCommentReplyMap.put(commentReplyPo.getId(), commentReplyPo);
            }
        }

        // 组装消息信息
        List<InteractMessageListVO> interactMessageListVo = new ArrayList<>(pageSize);
        for (NewestInteractMessagePO newestInteractMessagePO : interactMessagePoList) {
            InteractMessageListVO interactMessage = new InteractMessageListVO();
            //添加消息的id
            interactMessage.setId(newestInteractMessagePO.getId());
            //添加消息类型
            interactMessage.setType(newestInteractMessagePO.getType());
            //拼接用户信息 考虑为空情况
            UserPO userPO = userMap.get(newestInteractMessagePO.getUserId());
            if (userPO != null) {
                interactMessage.setNickname(userPO.getNickname());
                interactMessage.setAvatarUrl(userPO.getAvatarUrl());
                interactMessage.setUserId(userPO.getId());
                UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(userPO.getTitleNameId(), userPO.getTitleLogoId());
                //加入自己的头衔
                interactMessage.setUserTitlePO(userTitlePo);
            }
            //根据类型拼接合适的值
            //动态评论情况
            if (newestInteractMessagePO.getType() == ModuleType.DYNAMIC_COMMENT) {
                MessageDynamicCommentPO dynamicCommentPo = dynamicCommentMap.get(newestInteractMessagePO.getModuleId());
                if (dynamicCommentPo != null) {
                    interactMessage.setDynamicCommentId(newestInteractMessagePO.getSecondParentId());
                    interactMessage.setDynamicCommentContent(dynamicCommentPo.getContent());
                } else {
                    interactMessage.setDynamicCommentContent("");
                }
            } else if (newestInteractMessagePO.getType() == ModuleType.DYNAMIC_COMMENT_REPLY) {
                //获取动态回复内容
                MessageDynamicCommentReplyPO dynamicCommentReplyPo = dynamicCommentReplyMap.get(newestInteractMessagePO.getModuleId());
                MessageDynamicCommentPO messageDynamicCommentPO = dynamicCommentMap.get(newestInteractMessagePO.getSecondParentId());
                interactMessage.setDynamicReplyId(newestInteractMessagePO.getModuleId());
                interactMessage.setDynamicCommentId(newestInteractMessagePO.getSecondParentId());
                if (messageDynamicCommentPO != null) {
                    interactMessage.setDynamicCommentContent(messageDynamicCommentPO.getContent());
                }
                //如果是回复的回复
                if (newestInteractMessagePO.getZeroParentId() != null) {
                    interactMessage.setDynamicReplyContent(dynamicCommentReplyPo.getContent());
                    MessageDynamicCommentReplyPO messageDynamicCommentReplyPO = dynamicCommentReplyMap.get(newestInteractMessagePO.getFirstParentId());
                    if (messageDynamicCommentReplyPO != null) {
                        interactMessage.setDynamicCommentContent(messageDynamicCommentReplyPO.getContent());
                    }
                } else {
                    //如果是回复
                    if (dynamicCommentReplyPo != null) {
                        interactMessage.setDynamicReplyContent(dynamicCommentReplyPo.getContent());
                    } else {
                        interactMessage.setDynamicReplyContent("");
                    }
                }

            } else if (newestInteractMessagePO.getType() == ModuleType.DYNAMIC_COMMENT_LOVE) {
                MessageDynamicCommentPO messageDynamicCommentLovePO = dynamicCommentMap.get(newestInteractMessagePO.getSecondParentId());
                if (messageDynamicCommentLovePO != null) {
                    interactMessage.setDynamicCommentId(newestInteractMessagePO.getSecondParentId());
                    interactMessage.setDynamicCommentContent(messageDynamicCommentLovePO.getContent());
                } else {
                    interactMessage.setDynamicCommentContent("");
                }


            } else if (newestInteractMessagePO.getType() == ModuleType.DYNAMIC_COMMENT_REPLY_LOVE) {
                MessageDynamicCommentReplyPO messageDynamicCommentReplyLovePO = dynamicCommentReplyMap.get(newestInteractMessagePO.getFirstParentId());
                interactMessage.setDynamicReplyId(newestInteractMessagePO.getFirstParentId());
                interactMessage.setDynamicCommentId(newestInteractMessagePO.getSecondParentId());
                //评论内容加入
                MessageDynamicCommentPO messageDynamicCommentPO = dynamicCommentMap.get(newestInteractMessagePO.getSecondParentId());
                if (messageDynamicCommentPO != null) {
                    interactMessage.setDynamicCommentContent(messageDynamicCommentPO.getContent());
                }
                //看下是否修改修改评论内容改为上级的回复内容
                if (newestInteractMessagePO.getZeroParentId() != null) {
                    interactMessage.setDynamicReplyId(newestInteractMessagePO.getZeroParentId());
                    MessageDynamicCommentReplyPO messageDynamicCommentReplyPO = dynamicCommentReplyMap.get(newestInteractMessagePO.getFirstParentId());
                    if (messageDynamicCommentReplyPO != null) {
                        interactMessage.setDynamicCommentContent(messageDynamicCommentReplyPO.getContent());
                    }
                } else {
                    interactMessage.setDynamicReplyId(newestInteractMessagePO.getFirstParentId());
                }
                //加入回复内容
                if (messageDynamicCommentReplyLovePO != null) {
                    interactMessage.setDynamicReplyContent(messageDynamicCommentReplyLovePO.getContent());
                } else {
                    interactMessage.setDynamicReplyContent("");
                }
            }
            //添加问答 或者 动态
            ContentDetailsPO contentDetailsPO = contentDetailsMap.get(newestInteractMessagePO.getThirdParentId());
            if (contentDetailsPO != null) {
                interactMessage.setContentDetailsPo(contentDetailsPO);
                if (Integer.valueOf(AnonymousStatus.ANONYMOUS).equals(contentDetailsPO.getStatus()) &&
                    interactMessage.getUserId().equals(contentDetailsPO.getUserId())){
                    // 覆盖掉匿名主人信息
                    interactMessage.setUserId(null);
                    contentDetailsPO.setUserId(null);
                    interactMessage.setAvatarUrl(contentDetailsPO.getAvatarUrl());
                    interactMessage.setNickname(contentDetailsPO.getNickname());
                }
            } else {
                interactMessage.setContentDetailsPo(new ContentDetailsPO());
            }
            //添加时间
            interactMessage.setCreateTime(newestInteractMessagePO.getCreateTime());

            interactMessageListVo.add(interactMessage);
        }
        return interactMessageListVo;
    }


    /**
     * 根据互动消息各部分id， 查询最新一条互动消息的内容
     *
     * @param newestInteractMessagePo 初始参数
     * @return 最新互动消息
     */
    public NewestInteractMessageDetailsPO getOneNewestInteractMessage(NewestInteractMessagePO newestInteractMessagePo, UserPO userPo) {
        //获取用户信息
        NewestInteractMessageDetailsPO newestInteractMessageDetailsPo = new NewestInteractMessageDetailsPO();
        //查询该动态是否为匿名动态
        Dynamic dynamic = dynamicMapper.getDynamicById(newestInteractMessagePo.getThirdParentId());
        if (Integer.valueOf(AnonymousStatus.ANONYMOUS).equals(dynamic.getStatus())
           && dynamic.getUserId().equals(newestInteractMessagePo.getUserId())){
                //如果本人为匿名状态那么就应该任然显示匿名改动态为匿名状态，显示匿名信息
            Integer anonymousUserId = dynamic.getAnonymousUserId();
            AnonymousUser anonymousUser = anonyUserService.getAnonymousUserById(anonymousUserId);
            newestInteractMessageDetailsPo.setNickname(anonymousUser.getAnonymousName());
        }else {
            if (userPo != null) {
                newestInteractMessageDetailsPo.setNickname(userPo.getNickname());
            } else {
                newestInteractMessageDetailsPo.setNickname("");
            }
        }
        //判断消息的类型
        Short type = newestInteractMessagePo.getType();
        newestInteractMessageDetailsPo.setStatus(type);
        newestInteractMessageDetailsPo.setId(newestInteractMessagePo.getId());
        newestInteractMessageDetailsPo.setCreateTime(newestInteractMessagePo.getCreateTime());
        //获取评论回复的类型集合
        List<Short> contentList = Arrays.asList(MessageConstant.CONTENT_LIST);
        if (contentList.contains(type)) {
            //属于评论 、 回复的 一种
            if (type == ModuleType.DYNAMIC_COMMENT) {
                //动态评论数据
                String content = dynamicCommentMapper.getOneDynamicCommentContentByDynamicCommentId(newestInteractMessagePo.getModuleId());
                newestInteractMessageDetailsPo.setContent(content);
            }
            if (type == ModuleType.DYNAMIC_COMMENT_REPLY) {
                //动态评论回复
                String content = dynamicCommentReplyMapper.getOneDynamicCommentReplyContentByDynamicCommentReplyId(newestInteractMessagePo.getModuleId());
                newestInteractMessageDetailsPo.setContent(content);
            }
        }
        return newestInteractMessageDetailsPo;
    }

    /**
     * 保存消息
     *
     * @param userId         用户id
     * @param targetId       目标用户id
     * @param moduleId       模块id
     * @param moduleType     模块类型
     * @param firstParentId  一级父类id 动态id
     * @param secondParentId 二级父类id 动态评论id
     * @param thirdParentId  三级父类id 动态评论回复id
     */
    @Override
    public void saveMessage(Integer userId, Integer targetId, Integer moduleId, Short moduleType, Integer zeroParentId, Integer firstParentId, Integer secondParentId, Integer thirdParentId) {
        log.info("开始执行添加消息");
        // 添加到消息通知总表
        Message message = new Message();
        message.setType(moduleType);
        message.setUserId(userId);
        message.setTargetUserId(targetId);
        message.setModuleId(moduleId);
        message.setZeroParentId(zeroParentId);
        message.setFirstParentId(firstParentId);
        message.setSecondParentId(secondParentId);
        message.setThirdParentId(thirdParentId);
        message.setReadStatus(ReadStatus.UNREAD);
        Integer saveMessage = messageMapper.insertMessage(message);
        if (saveMessage == null || saveMessage == 0) {
            ExceptionUtils.error(MessageEnum.MESSAGE_CREATE_FAIL);
        }
    }

    @Override
    @Async("taskExecutor")
    public void deleteMessage(Integer userId, Integer moduleId, Short moduleType) {
        log.info("开始执行删除消息");
        //删除消息表中的消息
        //找到对应的父类
        Message message = new Message();
        message.setType(moduleType);
        message.setModuleId(moduleId);
        message.setUserId(userId);
        messageMapper.removeMessage(message);
    }


    @Override
    @Async("taskExecutor")
    public void deleteMessageByThirdParentId(Integer dynamicId, List<Short> type) {
        if (dynamicId != null && dynamicId > 0) {
            Integer integer = messageMapper.deleteMessageByThirdParentId(dynamicId, type);
            if (integer < DatabaseOperationResult.SUCCESS) {
                log.info("【删除失败】：三级父类对应的消息删除失败");
            } else {
                log.info("【删除成功】：三级父类对应的消息删除成功");
            }
            return;
        }
        ExceptionUtils.error(CommonEnum.REQUEST_PARAM_ERROR);
    }

    @Override
    @Async("taskExecutor")
    public void deleteMessageBySecondParentId(Integer dynamicCommentId, List<Short> type) {
        if (dynamicCommentId != null && dynamicCommentId > 0) {
            Integer integer = messageMapper.deleteMessageBySecondParent(dynamicCommentId, type);
            if (integer < DatabaseOperationResult.SUCCESS) {
                log.info("【删除失败】：二级父类对应的消息删除失败");
            } else {
                log.info("【删除成功】：二级父类对应的消息删除成功");
            }
            return;
        }
        ExceptionUtils.error(CommonEnum.REQUEST_PARAM_ERROR);
    }

    @Override
    @Async("taskExecutor")
    public void deleteMessageByFirstParentId(Integer dynamicCommentReplyId, List<Short> type) {
        if (dynamicCommentReplyId != null && dynamicCommentReplyId > 0) {
            Integer integer = messageMapper.deleteMessageByFirstParent(dynamicCommentReplyId, type);
            if (integer < DatabaseOperationResult.SUCCESS) {
                log.info("【删除失败】：一级父类对应的消息删除失败");
            } else {
                log.info("【删除成功】：一级父类对应的消息删除成功");
            }
            return;
        }
        ExceptionUtils.error(CommonEnum.REQUEST_PARAM_ERROR);
    }

    @Override
    @Async("taskExecutor")
    public void deleteMessageByZeroParentId(Integer dynamicDoubleReplyId, List<Short> type) {
        if (dynamicDoubleReplyId != null && dynamicDoubleReplyId > 0) {
            Integer integer = messageMapper.deleteMessageByZeroParent(dynamicDoubleReplyId, type);
            if (integer < DatabaseOperationResult.SUCCESS) {
                log.info("【删除失败】：一级父类对应的消息删除失败");
            } else {
                log.info("【删除成功】：一级父类对应的消息删除成功");
            }
            return;
        }
        ExceptionUtils.error(CommonEnum.REQUEST_PARAM_ERROR);
    }

}
